package edu.sctu.yueding.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import edu.sctu.yueding.R;
import edu.sctu.yueding.activitys.LoginActivity;
import edu.sctu.yueding.activitys.MyFriendsActivity;
import edu.sctu.yueding.activitys.MyInfoEditInfoActivity;
import edu.sctu.yueding.activitys.MyOrderListActivity;
import edu.sctu.yueding.activitys.MyQRCodeActivity;
import edu.sctu.yueding.activitys.MySignInActivity;
import edu.sctu.yueding.activitys.ScanResultAddFriendsActivity;
import edu.sctu.yueding.activitys.ScanResultGetPointActivity;
import edu.sctu.yueding.activitys.ScanResultGetTasksActivity;
import edu.sctu.yueding.activitys.SettingsActivity;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.utils.CompressImgUntil;
import edu.sctu.yueding.utils.JumpUtils;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;
import edu.sctu.yueding.view.CircleImageView;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;

/**
 * Created by Administrator on 2016/8/1.
 */
@SuppressLint("SdCardPath")
public class PersonalCenterFragment extends Fragment implements View.OnClickListener {

    private View view;
    private RelativeLayout mLineTwoRel, mLineThreeRel, mLineForeRel, mLineFiveRel, mLineSexRel, mLineSevenRel;
    private CircleImageView mHeadPhotoView;
    private TextView mLoginTextView, mNickName;

    private Activity mActivity;

    private Boolean isLogin;
    private SharePreference sharePreference;
    private String result = null;
    private ImageView newPoint;
    private String path;
    private ProgressBar bar;
    private CompressImgUntil compressImgUntil;
    boolean flag = false;

    // 要申请的权限
    private String[] permissions = {Manifest.permission.CAMERA};

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (view == null) {
            view = inflater.inflate(R.layout.personal_center_fragment, container, false);
            initView();


        }

        return view;
    }

    private void initView() {

        mActivity = getActivity();

        mLineTwoRel = (RelativeLayout) view.findViewById(R.id.id_personal_center_line_two_rel);
        mLineThreeRel = (RelativeLayout) view.findViewById(R.id.id_personal_center_line_there_rel);
        mLineForeRel = (RelativeLayout) view.findViewById(R.id.id_personal_center_line_fore_rel);
        mLineFiveRel = (RelativeLayout) view.findViewById(R.id.id_personal_center_line_five_rel);
        mLineSexRel = (RelativeLayout) view.findViewById(R.id.id_personal_center_line_sex_rel);
        mLineSevenRel = (RelativeLayout) view.findViewById(R.id.id_personal_center_line_seven_rel);
        newPoint = (ImageView) view.findViewById(R.id.new_point);
        bar = (ProgressBar) view.findViewById(R.id.portrait_bar);

        bar.setVisibility(View.GONE);
        newPoint.setVisibility(View.GONE);

        compressImgUntil = CompressImgUntil.getInstance();

        sharePreference = SharePreference.getInstance(mActivity);


        mHeadPhotoView = (CircleImageView) view.findViewById(R.id.id_personal_center_user_portrait);
        mLoginTextView = (TextView) view.findViewById(R.id.id_personal_center_login);
        mNickName = (TextView) view.findViewById(R.id.id_personal_center_nick_name);

        isLogin = JumpUtils.isLogin(mActivity);

        if (isLogin) {
            mLoginTextView.setText(null);
            initData();
        }

        setEvent();

        isRead();



    }



    private void isRead(){

        if (RongIM.getInstance() != null && sharePreference.getString(CacheConfig.CHAT_TOKEN) != null ) {
            /**
             * 接收未读消息的监听器。
             *
             * @param listener          接收所有未读消息消息的监听器。
             */
//            RongIM.getInstance().setOnReceiveUnreadCountChangedListener(new MyReceiveUnreadCountChangedListener());

            /**
             * 设置接收未读消息的监听器。
             *
             * @param listener          接收未读消息消息的监听器。
             * @param conversationTypes 接收指定会话类型的未读消息数。
             */
            RongIM.getInstance().setOnReceiveUnreadCountChangedListener(new MyReceiveUnreadCountChangedListener(), Conversation.ConversationType.PRIVATE);
        }


    }

    @Override
    public void onResume() {

        super.onResume();
        isRead();
        if (sharePreference.getBoolean(CacheConfig.IS_UPDATE_PORTRAIT)) {
            Log.e("5555", "55");
            initData();
            sharePreference.setCache(CacheConfig.IS_UPDATE_PORTRAIT, false);
        }

    }

    private void initData() {

        path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/悦定/";
        Bitmap bt = BitmapFactory.decodeFile(path + sharePreference.getString(CacheConfig.CACHE_USER_NAME) +"head.jpeg");//从Sd中找头像，转换成Bitmap
        if (bt != null && sharePreference.getBoolean(CacheConfig.IS_EQUALS_USER) && !sharePreference.getBoolean(CacheConfig.IS_UPDATE_PORTRAIT)) {
            @SuppressWarnings("deprecation")
            Drawable drawable = new BitmapDrawable(bt);//转换成drawable
            mHeadPhotoView.setImageDrawable(drawable);

        } else {
            /**
             *	如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
             *
             */

            bar.setVisibility(View.VISIBLE);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                    GetVolleyHttp.getInstance(mActivity).getBitmapByImageRequest(sharePreference.getString(CacheConfig.CACHE_PORTRAIT_PATH), new Response.Listener<Bitmap>() {
                        @Override
                        public void onResponse(Bitmap response) {

                            mHeadPhotoView.setImageBitmap(response);
                            bar.setVisibility(View.GONE);

                            compressImgUntil.saveBitmapToFile(response,sharePreference.getString(CacheConfig.CACHE_USER_NAME));
                        }
                    }, 0, 0, ImageView.ScaleType.CENTER, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

//                            mHeadPhotoView.setBackgroundResource(R.drawable.user_default_portrait);
                            bar.setVisibility(View.GONE);
                        }
                    });
                }
            }, 1000);
        }

        mNickName.setText(sharePreference.getString(CacheConfig.CACHE_NICKNMAE));
    }


    private void setEvent() {

        mLineTwoRel.setOnClickListener(this);
        mLineThreeRel.setOnClickListener(this);
        mLineForeRel.setOnClickListener(this);
        mLineFiveRel.setOnClickListener(this);
        mLineSexRel.setOnClickListener(this);

        mHeadPhotoView.setOnClickListener(this);
        mLineSevenRel.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        if (isLogin) {
            switch (v.getId()) {

                case R.id.id_personal_center_line_two_rel:

                    if (flag){

                        if (RongIM.getInstance() != null)

                            RongIM.getInstance().startConversationList(mActivity);
                    }else {

                        JumpUtils.jumpActivity(mActivity, MyFriendsActivity.class);
                    }

                    break;
                case R.id.id_personal_center_line_there_rel:
                    JumpUtils.jumpActivity(mActivity, MySignInActivity.class);
                    break;
                case R.id.id_personal_center_line_fore_rel:

                    // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                        // 检查该权限是否已经获取
                        int i = ContextCompat.checkSelfPermission(mActivity, permissions[0]);
                        // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                        if (i != PackageManager.PERMISSION_GRANTED) {
                            // 如果没有授予该权限，就去提示用户请求
//                        PermissionUtil.showDialogTipUserRequestPermission(mActivity, permissions);
                            ActivityCompat.requestPermissions(mActivity, permissions, 321);

                        } else {
                            startActivityForResult(new Intent(mActivity, CaptureActivity.class), 0);
                        }
                    } else {
                        startActivityForResult(new Intent(mActivity, CaptureActivity.class), 0);
                    }

                    break;
                case R.id.id_personal_center_line_five_rel:
                    JumpUtils.jumpActivity(mActivity, MyOrderListActivity.class);
                    break;
                case R.id.id_personal_center_line_sex_rel:
                    JumpUtils.jumpActivity(mActivity, MyQRCodeActivity.class);
                    break;
                case R.id.id_personal_center_line_seven_rel:
                    JumpUtils.jumpActivity(mActivity, SettingsActivity.class);
                    break;
                case R.id.id_personal_center_user_portrait:
                    JumpUtils.jumpActivity(mActivity, MyInfoEditInfoActivity.class);
                    break;

                default:
                    break;
            }
        } else {

            Toast.makeText(getActivity(), "请登录！", Toast.LENGTH_SHORT).show();
            JumpUtils.jumpActivity(mActivity, LoginActivity.class);
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == mActivity.RESULT_OK) {

            final Bundle bundle = data.getExtras();
            result = bundle.getString("result");
            boolean isBack = bundle.getBoolean("isBack");

            if (isBack) {
                Bundle bundle1 = new Bundle();
                bundle1.putInt("flag", 3);
                JumpUtils.activityToFragmentJump(getActivity(), bundle);
            }

            String[] re = result.split("/");
            Bundle bundle1 = new Bundle();
            bundle1.putString("result", result);
            int f = Integer.parseInt(re[re.length - 1]);

            if (f == 1) {
                JumpUtils.jumpActivity(mActivity, ScanResultGetTasksActivity.class, bundle1);
            } else if (f == 2) {
                JumpUtils.jumpActivity(mActivity, ScanResultGetPointActivity.class, bundle1);
            } else if (f == 3) {
                JumpUtils.jumpActivity(mActivity, ScanResultAddFriendsActivity.class, bundle1);
            }

        }


    }


    /**
     * 接收未读消息的监听器。
     */
    private class MyReceiveUnreadCountChangedListener implements RongIM.OnReceiveUnreadCountChangedListener {

        /**
         * @param count           未读消息数。
         */
        @Override
        public void onMessageIncreased(int count) {

            if (count > 0){
                 flag = true;
                newPoint.setVisibility(View.VISIBLE);
            }
        }
    }
}
